﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExportToWeb.CApExportToWebManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.PrivateImplementationDetails;


namespace DnProcessSimulateCommands.ExportToWeb;

internal class CApExportToWebManager
{
  private const string filename_cleanse = " \n\r\t`~!@#$%^&*()-+=\"\\':;,./<>?|[]{}±´";
  private IUiExportToWebDataProvider m_dataProvider;
  private CApC3DDataManagerApp m_dataManager = new CApC3DDataManagerApp();
  private CApC3DSnapshotApp m_snapshotApp = new CApC3DSnapshotApp();
  private CApExportSimulationManager m_simulationExporter;
  private CApC3DDocumentationSettings m_documentationSettings;
  private Hashtable m_filePaths = new Hashtable();
  private Hashtable m_fileNames = new Hashtable();
  private string m_AnimationDataFileName;
  private string m_AnimationFramesFileName;
  private string m_jsonDirectory;
  private bool m_exportSimulation;

  internal CApExportToWebManager(IUiExportToWebDataProvider dataProvider)
  {
    this.m_dataProvider = dataProvider;
    TxObjectList txObjectList = new TxObjectList();
    if (this.DataProvider.ApExportToWebViewModel.Operation != null)
    {
      ((Collection<ITxObject>) txObjectList).Add((ITxObject) this.DataProvider.ApExportToWebViewModel.Operation);
      TxApplication.ActiveSelection.Clear();
      TxApplication.ActiveSelection.AddItems(txObjectList);
    }
    this.m_dataManager.Initialize();
    this.m_documentationSettings = this.m_dataManager.GetDocumentationSettings();
    this.m_documentationSettings.PdfMode = (TxExportGraphicsAnimationFileFormatEx) 2;
    this.m_jsonDirectory = Path.GetDirectoryName(dataProvider.ExportToWebData_DestinationHTML);
  }

  internal IUiExportToWebDataProvider DataProvider
  {
    get => this.m_dataProvider;
    set => this.m_dataProvider = value;
  }

  internal CApC3DDocumentationSettings DocumentationSettings
  {
    get => this.m_documentationSettings;
    set => this.m_documentationSettings = value;
  }

  internal string AnimationDataFileName
  {
    get => this.m_AnimationDataFileName;
    set => this.m_AnimationDataFileName = value;
  }

  internal string AnimationFramesFileName
  {
    get => this.m_AnimationFramesFileName;
    set => this.m_AnimationFramesFileName = value;
  }

  public bool ExportSimulation
  {
    get => this.m_exportSimulation;
    set => this.m_exportSimulation = value;
  }

  internal bool Create()
  {
    bool flag = true;
    if (this.m_dataManager.Roots.Count == 0)
      return this.GenerateRoot(new CApC3DRootNodeData((ITxOperation) null));
    if (this.DataProvider.ApExportToWebViewModel != null && this.DataProvider.ApExportToWebViewModel.Operation == null)
    {
      this.DataProvider.ApExportToWebViewModel.Operation = (ITxOperation) null;
      return this.GenerateRoot(new CApC3DRootNodeData((ITxOperation) null));
    }
    int count = this.m_dataManager.Roots.Count;
    for (int index = 0; index < count & flag; ++index)
      flag = this.GenerateRoot(this.m_dataManager.Roots[index] as CApC3DRootNodeData);
    return flag;
  }

  private bool GenerateRoot(CApC3DRootNodeData rootNode)
  {
    bool root = true;
    TxObjectList objList = new TxObjectList();
    if (rootNode != null && (this.DataProvider.ApExportToWebViewModel == null || this.DataProvider.ApExportToWebViewModel.Operation == null || this.DataProvider.ApExportToWebViewModel.Operation == rootNode.NodeObject))
    {
      try
      {
        this.m_snapshotApp.CreateCurrentSnapshot();
        rootNode.AttachedSnapshotData = this.m_snapshotApp.CurrentSnapshot;
        string jsonDirectory = this.m_jsonDirectory;
        CApC3DAttachmentNameGenerator dattachmentNameGenerator = new CApC3DAttachmentNameGenerator();
        string path2_1 = "view.js";
        if (rootNode.PlanningNodeObject != null)
          path2_1 = dattachmentNameGenerator.GenerateAnimationFileName(rootNode.PlanningNodeObject, CApC3DUtils.JSExtension, false);
        string path2_2 = "frames_" + path2_1;
        string fileName = Path.Combine(jsonDirectory, path2_1);
        string simulationFileName = Path.Combine(jsonDirectory, path2_2);
        TxObjectList displayedObjects = new TxObjectList();
        CApC3DAppearanceSet appearanceSet = new CApC3DAppearanceSet();
        this.GetObjectsForExport((CApC3DProcessNodeData) rootNode, displayedObjects, appearanceSet, jsonDirectory);
        this.PrepareSceneForCreatingDataFile(displayedObjects);
        objList = this.BlankExcludedObjects();
        this.m_simulationExporter = new CApExportSimulationManager(rootNode, new TxExportGraphicsAnimationData()
        {
          JsonFiles = this.m_fileNames,
          OperationName = this.m_dataProvider.ExportToWebData_Operation,
          Description = "",
          Date = DateTime.Today.Date.ToString("YYYY.MM.dd"),
          StudyName = !TxTcUtilities.IsTcAnyPlatform ? ((ITxObject) TxApplication.ActiveDocument.CurrentStudy).Name : TxApplication.ActiveDocument.PhysicalRoot.Name
        }, (TxExportGraphicsAnimationFileFormatEx) 2, this.ExportSimulation);
        this.m_simulationExporter.SnapshotApp = this.m_snapshotApp;
        this.m_simulationExporter.InitializeWithGraphicExport(fileName, simulationFileName, this.DocumentationSettings, appearanceSet);
        if (this.ExportSimulation)
        {
          this.m_simulationExporter.ExportSimulation();
          this.m_simulationExporter.Terminate();
        }
        this.m_AnimationDataFileName = fileName;
        this.m_AnimationFramesFileName = simulationFileName;
      }
      catch (Exception ex)
      {
        throw;
      }
      finally
      {
        this.RestoreExcludedObjects(objList);
        this.m_snapshotApp.RestoreCurrentSnapshot(false);
        this.m_snapshotApp.DeleteTempSnapshots((CApC3DProcessNodeData) rootNode);
      }
    }
    return root;
  }

  private TxObjectList BlankExcludedObjects()
  {
    TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxCable)));
    TxObjectList txObjectList = new TxObjectList();
    TxApplicationEx.FireDocumentUpdateStarted();
    foreach (ITxDisplayableObject displayableObject in (Collection<ITxObject>) allDescendants)
    {
      if (displayableObject.Visibility == null)
      {
        ((Collection<ITxObject>) txObjectList).Add((ITxObject) displayableObject);
        displayableObject.Blank();
      }
    }
    return txObjectList;
  }

  private void RestoreExcludedObjects(TxObjectList objList)
  {
    foreach (ITxDisplayableObject displayableObject in (Collection<ITxObject>) objList)
      displayableObject.Display();
    TxApplicationEx.FireDocumentUpdateEnded();
  }

  private void GetObjectsForExport(
    CApC3DProcessNodeData operation,
    TxObjectList displayedObjects,
    CApC3DAppearanceSet appearanceSet,
    string path)
  {
    this.GetObjectsIncludedInSnapshots(displayedObjects, appearanceSet, true);
    this.GetObjectsIncludedInSimulationEvents(operation, displayedObjects, appearanceSet);
  }

  private void GetObjectsIncludedInSnapshots(
    TxObjectList displayedObjects,
    CApC3DAppearanceSet appearanceSet,
    bool currentlyVisibleOnly)
  {
    TxApplySnapshotParams applySnapshotParams = new TxApplySnapshotParams();
    applySnapshotParams.ObjectsLocation = true;
    applySnapshotParams.ObjectsVisibility = false;
    applySnapshotParams.PointOfView = false;
    applySnapshotParams.DevicePoses = false;
    applySnapshotParams.ObjectsAttachments = false;
    applySnapshotParams.ObjectsColor = true;
    applySnapshotParams.ObjectsViewingMode = false;
    applySnapshotParams.PMIsScale = true;
    TxObjectList txObjectList = new TxObjectList();
    ((Collection<ITxObject>) txObjectList).Add((ITxObject) this.m_snapshotApp.CurrentSnapshot.Snapshot);
    foreach (TxSnapshot snapshot in (Collection<ITxObject>) txObjectList)
    {
      snapshot.Apply(applySnapshotParams);
      foreach (ITxDisplayableObject visibleObject in (Collection<ITxObject>) snapshot.VisibleObjects)
      {
        if (!currentlyVisibleOnly)
          visibleObject.Display();
        if (visibleObject.Visibility == null || visibleObject.Visibility == 1)
          this.AddRelevantObjects(visibleObject, displayedObjects, appearanceSet, snapshot);
      }
    }
  }

  private void GetObjectsIncludedInSimulationEvents(
    CApC3DProcessNodeData operationNode,
    TxObjectList displayedObjects,
    CApC3DAppearanceSet appearanceSet)
  {
    if (operationNode.IsStep && operationNode.NodeObject is ITxSimulationEventParentOperation nodeObject)
    {
      List<ITxSimulationEventParentOperation> source = new List<ITxSimulationEventParentOperation>();
      source.Add(nodeObject);
      if (nodeObject is ITxObjectCollection objectCollection)
      {
        TxTypeFilter txTypeFilter = new TxTypeFilter(typeof (ITxSimulationEventParentOperation));
        source.AddRange(((IEnumerable) objectCollection.GetAllDescendants((ITxTypeFilter) txTypeFilter)).Cast<ITxSimulationEventParentOperation>());
      }
      new List<ITxDisplayableObject>(new List<ITxObject>(source.SelectMany<ITxSimulationEventParentOperation, ITxObject>((Func<ITxSimulationEventParentOperation, IEnumerable<ITxObject>>) (obj => (IEnumerable<ITxObject>) obj.SimulationEvents))).SelectMany<ITxObject, ITxObject>((Func<ITxObject, IEnumerable<ITxObject>>) (obj =>
      {
        TxDisplayEvent txDisplayEvent = obj as TxDisplayEvent;
        return TxDisplayEvent.op_Inequality(txDisplayEvent, (ITxObject) null) ? (IEnumerable<ITxObject>) txDisplayEvent.ObjectsToDisplay : Enumerable.Empty<ITxObject>();
      })).Cast<ITxDisplayableObject>()).ForEach((Action<ITxDisplayableObject>) (obj =>
      {
        obj.Display();
        if (obj.Visibility != null && obj.Visibility != 1)
          return;
        this.AddRelevantObjects(obj, displayedObjects, appearanceSet, operationNode.AttachedSnapshotData.Snapshot);
      }));
    }
    operationNode.GetChildren(true).ForEach((Action<CApC3DProcessNodeData>) (child => this.GetObjectsIncludedInSimulationEvents(child, displayedObjects, appearanceSet)));
  }

  private void AddRelevantObjects(
    ITxDisplayableObject obj,
    TxObjectList allDisplayedObjectsInSnapshots,
    CApC3DAppearanceSet appearanceSet,
    TxSnapshot snapshot)
  {
    if (!((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Contains((ITxObject) obj))
      ((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Add((ITxObject) obj);
    appearanceSet.AddAppearance(obj, snapshot);
    if (obj is ITxObjectCollection objectCollection)
    {
      foreach (ITxDisplayableObject allDescendant in (Collection<ITxObject>) objectCollection.GetAllDescendants((ITxTypeFilter) new TxNoTypeFilter()))
      {
        if (!((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Contains((ITxObject) allDescendant))
          ((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Add((ITxObject) allDescendant);
        appearanceSet.AddAppearance(allDescendant, snapshot);
      }
    }
    for (ITxDisplayableObject collection = ((ITxObject) obj).Collection as ITxDisplayableObject; collection != null; collection = ((ITxObject) collection).Collection as ITxDisplayableObject)
    {
      if (!((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Contains((ITxObject) collection))
        ((Collection<ITxObject>) allDisplayedObjectsInSnapshots).Add((ITxObject) collection);
    }
  }

  private void PrepareSceneForCreatingDataFile(TxObjectList displayedObjects)
  {
    foreach (ITxDisplayableObject displayedObject in (Collection<ITxObject>) displayedObjects)
    {
      if (displayedObject is ITxComponent)
      {
        ITxDisplayableObject displayableObject = displayedObject;
        if (displayableObject != null)
          displayableObject.DisplayMode = (TxDisplayMode) 1;
      }
    }
    TxApplication.RefreshDisplay();
  }
}
